import { Application } from "https://deno.land/x/oak@v12.6.0/mod.ts";
import authRouter from "./routes/auth.ts";
import linkRouter from "./routes/link.ts";
import ratingRouter from "./routes/rating.ts";
import { authMiddleware } from "./middlewares/authMiddleware.ts"; 
import { initDb } from "./db.ts";


const app = new Application();
const port: number = 7777;
//初始化db
await initDb();

// 中间件：CORS 配置
app.use(async (ctx, next) => {
  if (ctx.request.headers.get("Origin")) {
    ctx.response.headers.set("Access-Control-Allow-Origin", "*");
    ctx.response.headers.set(
      "Access-Control-Allow-Methods",
      "GET, POST, OPTIONS",
    );
    ctx.response.headers.set(
      "Access-Control-Allow-Headers",
      "Origin, X-Requested-With, Content-Type, Accept",
    );
  }
  if (ctx.request.method === "OPTIONS") {
    ctx.response.status = 200;
    return;
  }
  await next();
});

// 注册路由

app.use(linkRouter.routes());
app.use(linkRouter.allowedMethods());

app.use(authRouter.routes());

app.use(ratingRouter.routes());
app.use(ratingRouter.allowedMethods());


console.log(`Server is running on http://localhost:${port}`);
await app.listen({ port });
